<template>
  <!-- 状态图预览 -->
  <div class="mind">
    <div class="container" v-if="mermaidCode">
      <pre class="mermaid"
        >{{ mermaidCode }}
            </pre
      >
    </div>

    <!-- <div class="loading-text" v-if="!mermaidCode">状态图解析中,请稍后...</div> -->

    <!-- 如果 mermaidCode 为空且出现错误，显示错误提示 -->
    <div class="loading-text" v-if="!mermaidCode && errorText">{{ errorText }}</div>
    <div class="loading-text" v-if="!mermaidCode && !errorText">状态图解析中,请稍后...</div>
  </div>
</template>

<script setup lang="ts">
const emit: any = defineEmits(['getAiState']);
import mermaid from 'mermaid'; //引用mermaid
import { onMounted, ref } from 'vue';
const mermaidCode = ref();

const errorText = ref(''); // 存储错误信息
const retryCount = ref(0); // 记录失败的次数
const maxRetryCount = 5; // 最大重试次数
const initMermaidState = async (val: any) => {
  try {
    if (await mermaid.parse(val)) {
      mermaidCode.value = `${val}`;
      setTimeout(() => {
        nextTick(() => {
          mermaid.initialize({ startOnLoad: false });
          mermaid.init();
        });
      }, 1000);
      retryCount.value = 0; // 解析成功时重置计数器
      console.log('解析成功');
    }
  } catch (error) {
    retryCount.value += 1; // 解析失败时增加重试次数

    // 如果达到最大重试次数，提示用户
    if (retryCount.value >= maxRetryCount) {
      console.log('解析失败，达到最大重试次数');
      mermaidCode.value = ''; // 清空 mermaidCode，避免显示错误的内容
      errorText.value = '文本内容无法解析...'; // 设置错误提示信息
      return;
    }

    emit('getAiState');
    console.log('解析失败，正在重试...');
  }

  return;
};

onMounted(() => {});

defineExpose({
  initMermaidState
});
</script>

<style scoped lang="scss">
.mind {
  width: 100%;
  height: 100%;
  // display: flex;
  // flex-direction: column;
}

.loading-text {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 10px;
  font-size: 30px;
  color: #615ced;
  font-style: italic;
  animation: loading 1s infinite;
}

@keyframes loading {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

.svg-container {
  flex: 1;
  svg {
    width: 100%;
    height: 100%;
  }
}
.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}
.controls {
  margin-top: 10px;
}

.read-the-docs {
  color: #888;
}
</style>
